const ts = require('rollup-plugin-typescript2');
const json = require('@rollup/plugin-json')
const {nodeResolve} = require('@rollup/plugin-node-resolve');
const commonjs = require('@rollup/plugin-commonjs');

const path = require('path');
const packageFormats=process.env.FORMATS&&process.env.FORMATS.split(',');
const sourcemap=process.env.SOURCE_MAP;
const target=process.env.TARGET;
const packagesDir = path.resolve(__dirname, 'packages');
const packageDir = path.resolve(packagesDir, target);


const resolve = p=>path.resolve(packageDir, p);

const pkg = require(resolve('package.json'));
const outputConfig = {
    "esm-bundler": {
        file:resolve(`dist/${path.basename(packageDir)}.esm-bundle.js`),
        format:'es'
    },
    "cjs":{
        file:resolve(`dist/${path.basename(packageDir)}.cjs.js`),
        format:'cjs'
    },
    "global":{
        file:resolve(`dist/${path.basename(packageDir)}.global.js`),
        format:'iife',
    }
}
function createConfig(format,output) {
    output.sourcemap=sourcemap
    output.exports = 'named'
    let external=[]
    if(format==='global'){
        output.name=pkg.buildOptions.name
    }
    else{
        external=[...Object.keys(pkg.dependencies||{})]
    }
    return {
        input:resolve('src/index.ts'),
        output,
        external,
        plugins:[
            json(),
            ts(),
            commonjs(),
            nodeResolve()
        ]
    }
}

const packageConfigs = packageFormats || pkg.buildOptions.formats
module.exports = packageConfigs.map(format=>createConfig(format,outputConfig[format]))